package com.wyix;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author wangdx
 * @since 2025/8/5
 */
public class HttpGetDemo {
    public static void main(String[] args) throws IOException {
        // 1. 创建URL对象
        URL url = new URL("https://jsonplaceholder.typicode.com/users");

        // 2. 打开连接（未实际建立TCP连接）
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();


        // 3. 设置请求方法（默认GET，需大写）
        connection.setRequestMethod("GET");

        // 4. 设置请求头
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("User-Agent", "Java HttpURLConnection");

        // 5. 设置超时（毫秒）
        connection.setConnectTimeout(5000); // 连接超时
        connection.setReadTimeout(5000);    // 读取超时

        // 6. 发送请求（实际建立连接并发送数据）
        int responseCode = connection.getResponseCode();
        System.out.println("响应状态码: " + responseCode);

        // 7. 处理响应
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应体
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("响应内容: " + response.toString());
            }
        } else {
            System.out.println("请求失败: " + connection.getResponseMessage());
        }

        // 8. 关闭连接
        connection.disconnect();
    }
}
